/**
 * 
 */
package com.woupla.security;

import javax.ejb.Stateful;
import javax.enterprise.event.Event;
import javax.inject.Inject;
import javax.inject.Named;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.jboss.seam.international.status.Messages;
import org.jboss.seam.security.Authenticator;
import org.jboss.seam.security.BaseAuthenticator;
import org.jboss.seam.security.Credentials;
import org.jboss.seam.security.Identity;
import org.jboss.solder.logging.Logger;
import org.picketlink.idm.impl.api.PasswordCredential;
import org.picketlink.idm.impl.api.model.SimpleUser;

import com.woupla.account.Authenticated;
import com.woupla.account.UserType;
import com.woupla.model.User;

/**
 * @author Dimitri Lebel
 * 
 */
@Stateful
@Named
public class WouplaAuthenticator extends BaseAuthenticator implements
		Authenticator {
	@Inject
	private Logger log;

	@PersistenceContext
	private EntityManager em;

	@Inject
	private Identity identity;

	@Inject
	private Credentials credentials;

	@Inject
	private Messages messages;

	@Inject
	@Authenticated
	private Event<User> loginEventSrc;

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.jboss.seam.security.Authenticator#authenticate()
	 */
	@Override
	public void authenticate() {
		log.info("Logging in " + credentials.getUsername());
		if ((credentials.getUsername() == null)
				|| (credentials.getCredential() == null)) {
			// messages.error(new
			// DefaultBundleKey("identity_loginFailed")).defaults("Invalid username or password");
			setStatus(AuthenticationStatus.FAILURE);
		}
		Query query = em.createNamedQuery("findUserByPseudo", User.class);
		query.setParameter("pseudo", credentials.getUsername());
		User user = null;
		try {
			user = (User) query.getSingleResult();
		} catch (Exception e) {
			String message = "Tentative de connexion :" + e.getMessage();
			log.warn(message);
		}
		if (user != null
				&& credentials.getCredential() instanceof PasswordCredential
				&& user.getPassword().equals(((PasswordCredential) credentials.getCredential()).getValue())) {
			loginEventSrc.fire(user);
			if (user.getRole().equals(UserType.EMPLOYEE.getValue())) {
				identity.addGroup("EMPLOYEE", "GROUP");
			}
			else if (user.getRole().equals(UserType.MANAGER.getValue())) {
				identity.addRole("Manager", "EMPLOYEE", "GROUP");
			}
			// messages.info(new DefaultBundleKey("identity_loggedIn"),
			// user.getName()).defaults("You're signed in as {0}")
			// .params(user.getName());
			setStatus(AuthenticationStatus.SUCCESS);

			setUser(new SimpleUser(user.getPseudo())); // TODO confirm the need
														// for this set method
			return;
		}

		// messages.error(new
		// DefaultBundleKey("identity_loginFailed")).defaults("Invalid username or password");
		setStatus(AuthenticationStatus.FAILURE);

	}

}
